local Class = require('lua.lang.Class')
local File = require('lua.io.File')

--- @class Prototype : Class
--- @field k LuaValue[]
--- @field code number[]
--- @field lineInfo number[]
--- @field locVars LocalVariable[]
--- @field upvalues UpvalueDescriptor[]
--- @field source LuaString
--- @field lineDefined number
--- @field lastLineDefined number
--- @field numParams number
--- @field isVararg number
--- @field maxStackSize number
--- @field tailPos number
--- @field p Prototype[]
local Prototype = Class {}

--- @constructor
--- @return Prototype
function Prototype:new()
	--- @type Prototype
	local obj = {}
	obj.tailPos = -1
	obj.lineDefined = 0
	obj.lastLineDefined = 0
	obj.numParams = 0
	obj.isVararg = 0
	obj.maxStackSize = 0
	return setmetatable(obj, Prototype)
end

--- @param number number
--- @param pc number
--- @return LuaString
function Prototype:getLocalName(number, pc)
	local locVars = self.locVars
	local i = 1
	local length = #locVars
	while i <= length and locVars[i].startPc <= pc do
		local locVar = locVars[i]
		if pc < locVar.endPc then
			number = number - 1
			if number == 0 then
				return locVar.name
			end
		end
		i = i + 1
	end
	return nil
end

--- @return string
function Prototype:getShortSource()
	if self.source == nil then
		return 'null'
	end
	local name = self.source:toLString()
	if (not name:startsWith('/') or not File:new(name):exists()) and
			name:len() > 124 then
		name = name:sub(1, 125) .. '...'
	end
	if name:startsWith('@') or name:startsWith('=') then
		return name:sub(2)
	end
	if name:startsWith('\x1B') then
		return '=?'
	end
	return name
end

return Prototype